import { gutter } from "@/pages/const/keys";
import { download } from "@/utils/donwload";
import { InboxOutlined } from "@ant-design/icons";
import { request } from "@umijs/max";
import {
  Checkbox,
  Col,
  message,
  Modal,
  Row,
  UploadProps,
  Typography,
  UploadFile,
  GetProp,
} from "antd";
import Dragger from "antd/es/upload/Dragger";
import { useState } from "react";
const { Link, Text } = Typography;
type Props = {
  closed: () => void;
};
type FileType = Parameters<GetProp<UploadProps, "beforeUpload">>[0];

const App = (props: Props) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [uploading, setUploading] = useState(false);

  const [updateSupport, setUpdateSupport] = useState<boolean>(false);

  const handleUpload = async () => {
    try {
      const formData = new FormData();
      const [file] = fileList;
      formData.append("file", file as FileType);
      console.log(file, "fileList", fileList);
      if (!file) {
        message.error("请先选择文件");
        return;
      }
      // fileList.forEach((file) => {
      //   formData.append("file", file as FileType);
      // });
      setUploading(true);
      // You can use any AJAX library you like
      const { code, msg } = await request(
        `/api/system/user/importData?updateSupport=${updateSupport}`,
        {
          method: "POST",
          requestType: "form",
          data: formData,
        }
      );
      if (code === 200) {
        //恭喜您，数据已全部导入成功！共 2 条，数据如下：<br/>1、账号 test 导入成功<br/>2、账号 asdfasdfasdfasdf 导入成功

        props.closed();
        setUploading(false);
        setFileList([]);
        Modal.success({
          title: "导入成功",
          content: (
            <div
              dangerouslySetInnerHTML={{
                __html: msg,
              }}
            />
          ),
        });
      } else {
        // message.error(msg);
        Modal.error({
          title: "导入失败",
          content: (
            <div
              dangerouslySetInnerHTML={{
                __html: msg,
              }}
            />
          ),
        });
        setUploading(false);
        setFileList([]);
      }
    } catch (error) {
      message.error("导入失败");
      setUploading(false);
      setFileList([]);
    }
  };

  const uploadProps: UploadProps = {
    onRemove: (file) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: (file) => {
      //获取最后一个
      setFileList([...fileList, file].slice(-1));

      return false;
    },
    multiple: false,
    fileList,
    // name: "file",
    // multiple: false,

    // action: `/api/system/user/importData?${
    //   updateSupport ? "update=true" : "update=false"
    // }`,
    // onChange(info: { file: { name?: any; status?: any }; fileList: any }) {
    //   const { status } = info.file;
    //   if (status !== "uploading") {
    //     console.log(info.file, info.fileList);
    //   }
    //   if (status === "done") {
    //     console.log("info", info);
    //     // message.success(`${info.file.name} file uploaded successfully.`);
    //   } else if (status === "error") {
    //     message.error(`${info.file.name} file upload failed.`);
    //   }
    // },
    // onDrop(e: { dataTransfer: { files: any } }) {
    //   console.log("Dropped files", e.dataTransfer.files);
    // },
    // beforeUpload(file) {
    //   return;
    // },
  };
  const downloadTemplate = () => {
    download(
      "/api/system/user/importTemplate",
      {},
      `user_template_${new Date().getTime()}.xlsx`
    );
  };
  return (
    <Modal
      title="导入用户"
      open={true}
      onCancel={props.closed}
      onOk={handleUpload}
      cancelButtonProps={{
        disabled: uploading,
      }}
      okButtonProps={{
        disabled: uploading,
      }}
    >
      <Row gutter={[gutter, gutter]}>
        <Col span={24}>
          <Dragger {...uploadProps}>
            <p className="ant-upload-drag-icon">
              <InboxOutlined />
            </p>
            <p className="ant-upload-text">将文件拖到此处，或点击上传</p>
          </Dragger>
        </Col>
        <Col span={24}>
          <br />
          <br />
          <Checkbox
            checked={updateSupport}
            onChange={(e) => setUpdateSupport(e.target.checked)}
          >
            是否更新已经存在的用户数据
          </Checkbox>
        </Col>
        <Col span={24}>
          <Text>
            仅允许导入xls、xlsx格式文件。{" "}
            <Link onClick={downloadTemplate}>下载模板</Link>
          </Text>
        </Col>
      </Row>
    </Modal>
  );
};
export default App;
